package com.bghx.apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


public class Processor extends Thread {
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	//获取当前运行路径，组合成网页文件所在路径
	private final static String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webRoot";
	public Processor() {
		
	}
	
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream()); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void sendFile(String fileName){
		File file = new File(Processor.WEB_ROOT+fileName);
		if(!file.exists()
				|| !file.isFile()){
			sendErrorMessage(404, "File Not Exists");
			return;
		}
		try {
			FileInputStream in = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 ok");
			out.println("content-length:"+content.length);
			
			out.println();
			
			out.write(content);
			
			out.flush();
			out.close();//关闭输出
			in.close();//关闭输入
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}	
	
	private void sendErrorMessage(int code,String errorMessage){
		out.println("HTTP/1.0 "+code+" "+errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode: "+code+" ErrorMessage: "+errorMessage);
		out.println("</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String parse(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			//获取第一行
			String httpMessage = br.readLine();
		
			String[] content = httpMessage.split(" ");
			if(content.length != 3){
				//第一行的格式不正确，返回错误信息
				sendErrorMessage(400,"Client query error!");
				return null;
			}
			return content[1];//返回请求的文件名
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	public void run() {
		String fileName = parse(in);
		sendFile(fileName);
	}	
	
}
